package com.san.dissertation.dao.repository.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.san.dissertation.bpm.model.Process;
import com.san.dissertation.bpm.model.ProcessInstance;
import com.san.dissertation.bpm.model.ProcessPath;
import com.san.dissertation.bpm.model.Task;
import com.san.dissertation.dao.repository.ProcessInstanceRepostitoryCustom;
import com.san.dissertation.dao.repository.ProcessPathRepostitoryCustom;

public class ProcessInstanceRepositoryImpl implements ProcessInstanceRepostitoryCustom {

	@Autowired
	private MongoTemplate mongoTemplate;

	public void updateStartTaskEnd(Process process, String taskId) {
		// TODO Auto-generated method stub
		
		Query query= new Query();
		query.addCriteria(Criteria.where("process").is(process));
		
		ProcessInstance processInstance=mongoTemplate.findOne(query, ProcessInstance.class);
		
		System.out.println("////////"+processInstance);
		
		
		for(Task pathTask: processInstance.getTask()){
			
			if(pathTask.getId().equals(taskId)){
				
				pathTask.setEndDate(new Date());
				int duration= Integer.valueOf(Long.toString(pathTask.getEndDate().getTime()-pathTask.getStartDate().getTime()));
				pathTask.setDuration(duration);
			}
			
		}
		
		mongoTemplate.save(processInstance);
		
	}

	public ProcessInstance getProcessInstanceById(String instanceId) {

		Query query= new Query();
		query.addCriteria(Criteria.where("_id").is(instanceId));
		
		ProcessInstance processInstance=mongoTemplate.findOne(query, ProcessInstance.class);
		
		System.out.println("////////"+processInstance);
		
		
		return processInstance;
	}

	public void updateEndTaskEnd(Process process, String taskId) {
		// TODO Auto-generated method stub
		
		Query query= new Query();
		query.addCriteria(Criteria.where("process").is(process));
		
		ProcessInstance processInstance=mongoTemplate.findOne(query, ProcessInstance.class);
		
		System.out.println("////////"+processInstance);
		processInstance.setEndDate(new Date());
		
		for(Task pathTask: processInstance.getTask()){
			
			if(pathTask.getId().equals(taskId)){
				
				pathTask.setEndDate(new Date());
				int duration= Integer.valueOf(Long.toString(pathTask.getEndDate().getTime()-pathTask.getStartDate().getTime()));
				pathTask.setDuration(duration);
			}
			
		}
		
		mongoTemplate.save(processInstance);
		
	}

	public List<ProcessInstance> getProcessInstanceByProcess(Process process) {
		// TODO Auto-generated method stub
		
		Query query= new Query();
		query.addCriteria(Criteria.where("process").is(process));
		
		List<ProcessInstance> processInstances=mongoTemplate.find(query, ProcessInstance.class);
		
		
		return processInstances;
	}

	

}
